﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Bridge.Workflow.Extensions;
using Bridge.Workflow.Localization;
using Bridge.Workflow.Settings;
using Localization.Resources.AbpUi;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Volo.Abp;
using Volo.Abp.AspNetCore.Mvc;
using Volo.Abp.Localization;
using Volo.Abp.Modularity;

namespace Bridge.Workflow
{
    [DependsOn(
        typeof(WorkflowApplicationContractsModule),
        typeof(AbpAspNetCoreMvcModule),
        typeof(WorkflowHttpApiClientModule)
        )]
    public class WorkflowHttpApiModule : AbpModule
    {
        public override void PreConfigureServices(ServiceConfigurationContext context)
        {
            PreConfigure<IMvcBuilder>(mvcBuilder =>
            {
                mvcBuilder.AddApplicationPartIfNotExists(typeof(WorkflowHttpApiModule).Assembly);
            });
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        public override void ConfigureServices(ServiceConfigurationContext context)
        {
            var configuration = context.Services.GetConfiguration();
            Configure<AbpLocalizationOptions>(options =>
            {
                options.Resources.Get<WorkflowResource>().AddBaseTypes(typeof(AbpUiResource));
            });
            context.Services.AddSwagger();

            context.Services.Configure<Setting>(configuration.GetSection(key: "AuthServer"));
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        public override void OnApplicationInitialization(ApplicationInitializationContext context)
        {
            var app = context.GetApplicationBuilder();

            app.UseSwaggerUI();

            //app.UseMiddleware()

            //app.UseHangfireServerExt(HangFireJob.InintJob).UseHangfireDashboardExt();

            //app.UseLogDashboard();

            var serviceSelector = context.ServiceProvider.GetService<IAbpWorkflowRegistry>();

            var referencedAssembly = typeof(WorkflowApplicationContractsModule).Assembly;
            var baseInterfaceTypes = new List<Type> { typeof(IAbpWorkflow) };
            IEnumerable<Type> implementTypes = referencedAssembly.DefinedTypes.Select(type => type.AsType()).Where(x => x.IsClass);
            //IEnumerable<Type> implementTypes = types;

            foreach (var implementType in implementTypes)
            {
                if (!typeof(IAbpWorkflow).GetTypeInfo().IsAssignableFrom(implementType))
                {
                    continue;
                }

                serviceSelector.RegisterWorkflow(implementType);
            }
        }
    }
}
